﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using DevComponents.DotNetBar;

namespace SC.AddFlow
{
    public sealed partial class Form1 : OfficeForm
    {
        private List<string> _lsUrls = new List<string>();
        private bool _isStop = false;

        public Form1()
        {
            InitializeComponent();
            EnableGlass = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            webBrowser1.ScriptErrorsSuppressed = true;
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            webBrowser1.Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);

        }

        void Window_Error(object sender, HtmlElementErrorEventArgs e)
        {
            e.Handled = true;
        }

        // this.webBrowser1.ScriptErrorsSuppressed = true;   //屏蔽js相关错误。。。
        private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        #region 委托事件--进度条和状态更新

        delegate void LabDelegate(string str);

        private void SetLabelText(string str)
        {
            if (labState.InvokeRequired)
            {
                Invoke(new LabDelegate(SetLabelText), str);
            }
            else
            {
                labState.Text = str;
            }
        }

        private delegate void PbDelegate(int value);

        private void SetPbValue(int value)
        {
            if (progressBar1.InvokeRequired)
            {
                Invoke(new PbDelegate(SetPbValue), value);

            }
            else
            {
                progressBar1.Value = value;
            }
        }

        #endregion

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtUrls.Text))
            {
                MessageBox.Show("请先添加URL!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            _lsUrls = txtUrls.Text.TrimEnd(';').Replace("\r\n", "").Split(';').ToList();
            if (!_lsUrls.Any())
            {
                MessageBox.Show("请先添加URL!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (string.IsNullOrEmpty(txtCount.Text))
            {
                MessageBox.Show("尚未输入总次数!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (string.IsNullOrEmpty(txtTime.Text))
            {
                MessageBox.Show("尚未输入时间间隔!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }


            btnStart.Enabled = false;
            Thread thread = new Thread(StartAdd) { IsBackground = true };
            thread.Start();

            progressBar1.Minimum = 0;
            progressBar1.Maximum = int.Parse(txtCount.Text);
            SetPbValue(0);

        }

        /// <summary>
        /// 开始事件
        /// </summary>
        private void StartAdd()
        {
            try
            {
                SetPbValue(0);
                SetLabelText("正在操作！");
                int waitTime = int.Parse(txtTime.Text) * 1000;
                int addCount = int.Parse(txtCount.Text);
                _isStop = false;
                for (int j = 1; j <= addCount; j++)
                {
                    if (!_isStop)
                    {
                        foreach (string url in _lsUrls)
                        {
                            if (!_isStop)
                            {
                                var uri = url;
                                if (!uri.Contains("http://") && !uri.Contains("www."))
                                    uri = "http://www." + url;
                                if (!uri.Contains("www."))
                                    uri = "www." + url;
                                if (!uri.Contains("http://"))
                                    uri = "http://" + url;
                                webBrowser1.Url = new Uri(uri);
                                Thread.Sleep(waitTime);
                            }
                            else
                            {
                                break;
                            }
                        }
                        SetPbValue(j);
                        SetLabelText("当前执行第" + j + "次操作！已完成：" + Math.Round((double)j / (double)addCount, 2) * 100 + "%");
                    }
                    else
                    {
                        break;
                    }
                }
                BeginInvoke(new MethodInvoker(delegate ()
                {
                    btnStart.Enabled = true;
                }));
            }
            catch (Exception ex)
            {
                BeginInvoke(new MethodInvoker(delegate ()
                {
                    btnStart.Enabled = true;
                }));
                MessageBox.Show("程序出现异常：" + ex.ToString(), "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }


        /// <summary>
        /// 终止操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, EventArgs e)
        {
            _isStop = true;
            btnStart.Enabled = true;
            labState.Text = "已终止操作！";
        }

        private void txtBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            //如果输入的不是数字键，也不是回车键、Backspace键，则取消该输入
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)13 && e.KeyChar != (char)8)
            {
                e.Handled = true;
            }
        }

        private void Form1_HelpButtonClicked(object sender, CancelEventArgs e)
        {
            System.Diagnostics.Process.Start("http://ctacy.cc/");
        }
    }
}
